//
//  SearchPage_Vc.swift
//  Pods
//
//  Created by eme on 2017/3/29.
//
//


/*
 owner:cy
 update:2017年03月29日08:57:21
 info: 登陆界面
 model: UserModel
 viewmodel: LoginViewModel
 */
import RxSwift
import UtilCore
import RickonCore

let tagLabel_margin:CGFloat = 10 // 默认边距

class SearchPage_Vc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    //存放热门搜索标签的容器
    @IBOutlet weak var tagKeyWordContent_V:UIView!
    
    @IBOutlet weak var search_bar: UISearchBar!
    @IBOutlet weak var search_Tv: UITableView!
    var hotKeyArr:[String] = []{
        didSet{
            self.search_Tv.reloadData()
        }
    }
    var historyKeyArr:[String] = []{
        didSet{
            self.setupHotHistoryRectangleTags()
        }
    }
    var manageVm:SearchPage_Vm?
    var keyword:String?
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    lazy var rightBtn: UIButton = {
        let button = UIButton()
        button.frame = CGRect(x: 0, y: 0, width: 45, height: 35)
        button.contentHorizontalAlignment = .center
        button.setTitle("取消", for: .normal)
        button.titleLabel?.font = UIFont(name: Theme.fontName, size: 15)
        button.setTitleColor(Theme.robb.searchPage.cancle_btn, for: .normal)
        return button
    }()
    
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.historyKeyArr = SearechKeyWordTool.sharedInstance.readFromFind()
        self.search_bar.becomeFirstResponder()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SearechKeyWordTool.sharedInstance.writeToFind(arr: self.historyKeyArr)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
    }
    /**
     自定义leftBarButtonItem
     */
    override func customLeftBarButtonItem()  {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
        let  rightItem = UIBarButtonItem(customView: self.rightBtn)
        self.navigationItem.rightBarButtonItem = rightItem
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        self.search_bar.backgroundImage = UIImage()
        self.search_bar.tintColor =  UIColor(hex: "444444")
        self.search_bar.placeholder = placeKeyWork
        self.search_bar.backgroundColor = UIColor.clear
        self.search_bar.keyboardType = UIKeyboardType.default
        self.search_bar.delegate = self
        self.search_bar.contentMode = .left
        ///隐藏滑动条
        self.search_Tv.showsVerticalScrollIndicator = false
        self.search_bar.text = self.keyword
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        self.manageVm = SearchPage_Vm(refreshTriger: rx.sentMessage(#selector(SearchPage_Vc.viewWillAppear)).map { _ in () })
        self.manageVm?
            .error
            .bindTo(self.view.rx_error)
            .disposed(by: disposeBag)
        self.manageVm?
            .keyItems
            .asObservable()
            .subscribe(onNext: { [unowned self] (keyList) in
                self.hotKeyArr = keyList
            })
            .disposed(by: disposeBag)
        self.rightBtn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                self.search_bar.resignFirstResponder()
                self.backToView()
            })
            .disposed(by: disposeBag)
        
    }
}
extension SearchPage_Vc{
    /// 更新tableview的headerview显示数据
    func setupHotHistoryRectangleTags() -> Void {
        /// 第一步先删除之前添加的所有的子视图
        for subView in self.tagKeyWordContent_V.subviews {
            subView.removeFromSuperview()
        }
        var currentX:CGFloat = 0
        var currentY:CGFloat = 0
        var countRow:CGFloat = 0
        var countCol:CGFloat = 0
        /// 判断是否包含有历史搜索数据
        if self.historyKeyArr.count > 0 {
            /// 设置清楚按钮
            let history_Lb = UILabel()
            history_Lb.isUserInteractionEnabled = true
            history_Lb.textAlignment = .left
            history_Lb.font = UIFont(name: "Helvetica", size: 15)
            history_Lb.text = "最近搜索"
            history_Lb.sizeToFit()
            history_Lb.v_x = 0
            history_Lb.v_y = tagLabel_margin
            self.tagKeyWordContent_V.addSubview(history_Lb)
            /// 设置清楚按钮
            let history_Btn = UIButton(type: .custom)
            history_Btn.setImage(UIImage(named: "search-clear-btn"), for: .normal)
            history_Btn.sizeToFit()
            history_Btn.v_y = tagLabel_margin
            history_Btn.v_x = self.tagKeyWordContent_V.v_width - tagLabel_margin - history_Btn.v_width
            history_Btn.addTarget(self, action: #selector(SearchPage_Vc.clearHistoryData), for: .touchUpInside)
            self.tagKeyWordContent_V.addSubview(history_Btn)
            currentY = history_Lb.v_y + history_Lb.v_hegith + tagLabel_margin
        }
        var isremove:Bool = false
        for item in  self.historyKeyArr.enumerated(){
            if isremove {
                break
            }
            let tagLabel = labelWithTitle(title: item.element)
            tagLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(SearchPage_Vc.tagDidCLick)))
            self.tagKeyWordContent_V.addSubview(tagLabel)
            //调整label的位置
            // 当搜索字数过多，宽度为contentView的宽度
            if tagLabel.v_width > self.tagKeyWordContent_V.v_width {
                tagLabel.v_width = self.tagKeyWordContent_V.v_width
            }
            /// 换行
            if currentX + tagLabel.v_width + tagLabel_margin * countRow > self.tagKeyWordContent_V.v_width {
                countCol = countCol + 1
                /// 最多现实三行
                if countCol > 2 {
                    isremove = true
                    tagLabel.removeFromSuperview()
                }else{
                    tagLabel.v_x = 0
                    currentY = currentY + tagLabel.v_hegith
                    tagLabel.v_y = currentY + tagLabel_margin * countCol
                    currentX = tagLabel.v_width
                    countRow = 1
                }
            }else{
                //不换行
                currentX = currentX + tagLabel.v_width
                tagLabel.v_x = currentX - tagLabel.v_width + tagLabel_margin * countRow
                tagLabel.v_y = currentY + tagLabel_margin * countCol
                countRow = countRow + 1
            }
        }
        if let lastFrame = self.tagKeyWordContent_V.subviews.last?.frame {
            self.tagKeyWordContent_V.v_hegith = lastFrame.maxY
            self.search_Tv.tableHeaderView!.v_hegith = self.tagKeyWordContent_V.frame.maxY + tagLabel_margin * 2
            self.search_Tv.tableHeaderView =  self.search_Tv.tableHeaderView
        }else{
            self.search_Tv.tableHeaderView!.v_hegith = 0
            self.search_Tv.tableHeaderView =  self.search_Tv.tableHeaderView
        }
    }
    /// 创建label标签
    func labelWithTitle(title:String) -> UILabel {
        let tagLabel = UILabel()
        tagLabel.isUserInteractionEnabled = true
        tagLabel.textAlignment = .center
        tagLabel.font = UIFont(name: "Helvetica", size: 13)
        tagLabel.layer.cornerRadius = 3
        tagLabel.clipsToBounds = true
        tagLabel.textColor = UIColor(hex: "333333")
        tagLabel.text = title
        tagLabel.backgroundColor = UIColor.clear
        tagLabel.layer.borderColor = UIColor(hex: "dcdcdc").cgColor
        tagLabel.layer.borderWidth = 0.5
        tagLabel.sizeToFit()
        tagLabel.v_width += 16
        tagLabel.v_hegith += 10
        return tagLabel
    }
    /// 点击标签触发事件
    func tagDidCLick(tap:UITapGestureRecognizer) -> Void {
        if let  label = tap.view as? UILabel {
            self.search_bar.text = label.text
            self.keyword = label.text
            self.search_bar.resignFirstResponder()
            _ = "searchproducts".openURL(["keyWord":label.text ?? ""])
        }
    }
    func clearHistoryData() -> Void {
        self.historyKeyArr.removeAll()
    }
}

extension SearchPage_Vc :UISearchBarDelegate{
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        guard let searchText = searchBar.text, searchText.characters.count > 0 else {
            return
        }
        searchBar.resignFirstResponder()
        guard searchText.characters.count < 100 else {
            showMsg(100011002)
            return
        }
        if self.historyKeyArr.count > 0 {
            if !self.historyKeyArr.contains(searchText) {
                self.historyKeyArr.insert(searchText, at: 0)
            }else{
                // 包含 searchText ，需要将searchText 放置到0位置
                
            }
        }else{
            self.historyKeyArr = [searchText]
        }
        _ = "searchproducts".openURL(["keyWord":searchText])
    }
}
// MARK: UITableViewDelegate
extension SearchPage_Vc :UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return self.hotKeyArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "HotKey_TCell", for: indexPath) as! HotKey_TCell
        cell.item = self.hotKeyArr[indexPath.row]
        return cell
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.hotKeyArr.count == 0 {
            return 0
        }else{
            return 1
        }
    }
    /*
     // fixed font style. use custom view (UILabel) if you want something different
     func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?{
     
     }
     func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String?{
     
     }
     */
    
}
// MARK: UITableViewDelegate
extension SearchPage_Vc: UITableViewDelegate {
    /// 点击行事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        self.search_bar.resignFirstResponder()
        let searchText = self.hotKeyArr[indexPath.row]
        self.search_bar.text = searchText
        _ = "searchproducts".openURL(["keyWord":searchText])
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return 45
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 50
    }
    ///自定义view
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let cell = self.search_Tv.dequeueReusableCell(withIdentifier: "HotTCell")
        return cell
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView){
        self.search_bar.resignFirstResponder()
    }
    
}
